package com.shipwe.loans.ui.activity

import android.content.Intent
import android.graphics.Color
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.shipwe.loans.R
import com.shipwe.loans.databinding.ActivityUserInfoBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.presenter.UploadPresenter
import com.shipwe.loans.ui.view.IUploadView
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.dialog.PhotoDialog
import com.shipwe.loans.utils.event.AppEventData
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomDataHelper
import com.shipwe.loans.utils.imgcovert.ImageConvert
import com.shipwe.loans.utils.log.ShipweLogger

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/28 18:11
 * @Annotation：个人信息
 */
class ActivityUserInfo: ShipweActivity(), IUploadView {
    lateinit var binding: ActivityUserInfoBinding
    private var presenter: UploadPresenter? = null

    private var photoDialog: PhotoDialog? = null
    //图片选择
    lateinit var pickMedia: ActivityResultLauncher<PickVisualMediaRequest>

    override fun getShipweRootView(): View {
        binding = ActivityUserInfoBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundColor(Color.parseColor("#F9F9F9"))
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweTextTitle(getString(R.string.user_info_title))
        setShipweRightBtnRes(R.drawable.customer_black)
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("User Information Page")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"User Information Page")
            if (binding.userInfoName.isFocused){
                binding.userInfoName.clearFocus()
            }
        }
        binding.parentLayout.setOnClickListener {
            if (binding.userInfoName.isFocused){
                binding.userInfoName.clearFocus()
            }
        }
        binding.userInfoHeader.setOnClickListener {
            if (binding.userInfoName.isFocused){
                binding.userInfoName.clearFocus()
            }
            if (presenter == null){
                presenter = UploadPresenter(this)
            }
            showUserInfoPhotoDialog("User Information Page")
        }
        //昵称
        binding.userInfoName.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {//获得焦点
                }
                else -> {//失去焦点
                    val userName = binding.userInfoName.text.toString().trim()
                    if (userName.isNotEmpty()){
                        CustomDataHelper.saveShipweCustomUserNameAction(userName)
                    }
                }
            }
        }

        binding.userInfoName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.userInfoName.clearFocus()
                true
            }
            false
        }

        // 1-注册图库组件
        pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
            if (uri != null) {
                // 图片处理
                ImageConvert.covert(context = this, uri = uri) { localPath, bitmap ->
                    if (localPath != null){
                        ShipweLogger.e(">>>>>>>album>>>>>>>>>>$localPath")
                        showShipweLoading(isTOuchOut = false, isCancel = false)
                        presenter!!.submitUploadImageAction(localPath)
                    }
                }
            } else {
                ShipweLogger.e("No media selected")
            }
        }
    }

    override fun initShipweData() {
        setUserInfoData()
    }

    /**
     * 设置用户信息
     */
    private fun setUserInfoData(){
        val avatarUrl = CustomDataHelper.getShipweCustomUserAvatarUrl()
        if (avatarUrl.isNotEmpty()){
            AppLoadImageUtil.instance.loadImageUrl(this,binding.userInfoHeader,avatarUrl)
        } else {
            binding.userInfoHeader.setImageResource(R.drawable.load_holder)
        }
        binding.userInfoName.setText(CustomDataHelper.getShipweCustomUserName())
    }

    /**
     * 相机、相册
     */
    private fun showUserInfoPhotoDialog(eventRemark: String){
        if (photoDialog == null){
            photoDialog = PhotoDialog(this,eventRemark,object : PhotoDialog.IDialogCallback{
                override fun openCamera() {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CAMERA,eventRemark)
                    openUserInfoCamera()
                }
                override fun openAlbum() {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_ALBUM,eventRemark)
                    openUserInfoAlbum()
                }
            })
            photoDialog!!.setCancelable(true)
            photoDialog!!.setCanceledOnTouchOutside(true)
        }
        photoDialog!!.show()
    }

    /**
     * 打开相册
     */
    private fun openUserInfoAlbum(){
        pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
    }

    /**
     * 打开相机
     */
    private fun openUserInfoCamera(){
        faceCameraResultLauncher.launch(Intent(this, ActivityCameraFace::class.java))
    }

    /**
     * 人脸拍照
     */
    private val faceCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                val faceImgPath = result.data!!.getStringExtra("imgLocalPath").toString()
                ShipweLogger.e(">>>>>>>>>face info ：$faceImgPath")
                val imgLocalPath = result.data!!.getStringExtra("imgLocalPath").toString()
                val imgUrl = result.data!!.getStringExtra("imgUrl").toString()
                CustomDataHelper.saveShipweCustomUserAvatar(imgUrl)
            }
        }
    }

    /**
     * 图片上传成功
     */
    override fun showUploadImageSuccess(imgPath: String, imgUrl: String) {
        CustomDataHelper.saveShipweCustomUserAvatar(imgUrl)
    }

    override fun onShipwePublishEvent(event: AppEventData) {
        super.onShipwePublishEvent(event)
        when(event.eventType){
            AppEventData.TYPE.SHIPWE_CUSTOM_DATA_REFRESHED -> {//自定义数据刷新完成
                //设置用户昵称和头像
                setUserInfoData()
            }
            else -> {

            }
        }
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_USER_INFORMATION_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_USER_INFORMATION_END)
    }
}